﻿using System;
using System.Configuration;
using System.IO;
using System.Web;

namespace TidyBlog.MVC.WWW
{
    /// <summary>
    /// 附件中转页
    /// </summary>
    public class FileTransfer : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string fileName = context.Request.QueryString["fileName"];

            if (!String.IsNullOrEmpty(fileName))
            {
                context.Response.Clear();
                context.Response.ClearHeaders();

                /*string referHost = null;
                if (context.Request.UrlReferrer != null)
                {
                    referHost = context.Request.UrlReferrer.Host.ToLower();
                }

                bool isValidRefer = false;
                string siteDomain = SetupBLL.Read().SiteDomain.ToLower();
                if (!String.IsNullOrEmpty(referHost) && (referHost == siteDomain || referHost.EndsWith("." + siteDomain) || referHost == "localhost"))
                {
                    isValidRefer = true;
                }*/

                /*if (isValidRefer)
                {*/
                    FileInfo file = new FileInfo(
                        context.Server.MapPath(ConfigurationManager.AppSettings["AttachmentFolder"] + fileName.Substring(0, 6) + "/" + fileName)
                    );

                    if (file.Exists)
                    {
                        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                        context.Response.AddHeader("Content-Length", file.Length.ToString());
                        context.Response.ContentType = "application/octet-stream";
                        context.Response.Cache.SetExpires(DateTime.UtcNow.AddMonths(1));
                        context.Response.TransmitFile(file.FullName);
                    }
                    else
                    {
                        context.Response.ContentType = "text/plain";
                        context.Response.Write("File Not Found");
                    }
                /*}
                else
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("Hot Link Protection: " + referHost);
                }*/
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}